package com.lncd.backend.controller;

import com.lncd.backend.dto.LocationDTO;
import com.lncd.backend.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/locations")
public class LocationController {

    private final LocationService locationService;

    @Autowired
    public LocationController(LocationService locationService) {
        this.locationService = locationService;
    }

    @PostMapping
    public ResponseEntity<LocationDTO> addLocation(@RequestBody LocationDTO locationDTO) {
        try {
            LocationDTO addedLocation = locationService.addLocation(locationDTO);
            return ResponseEntity.ok(addedLocation);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<LocationDTO> getLocationById(@PathVariable Long id) {
        try {
            LocationDTO location = locationService.getLocationById(id);
            return ResponseEntity.ok(location);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<LocationDTO>> getLocationsByUserId(
            @PathVariable Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date endTime) {
        try {
            if (startTime != null && endTime != null) {
                List<LocationDTO> locations = locationService.getLocationsByUserIdAndTimeRange(userId, startTime, endTime);
                return ResponseEntity.ok(locations);
            } else {
                List<LocationDTO> locations = locationService.getLocationsByUserId(userId);
                return ResponseEntity.ok(locations);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @GetMapping("/user/{userId}/latest")
    public ResponseEntity<LocationDTO> getLatestLocationByUserId(@PathVariable Long userId) {
        try {
            LocationDTO location = locationService.getLatestLocationByUserId(userId);
            return ResponseEntity.ok(location);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, String>> deleteLocation(@PathVariable Long id) {
        try {
            locationService.deleteLocation(id);
            Map<String, String> response = new HashMap<>();
            response.put("message", "位置信息删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    @PostMapping("/simple")
    public ResponseEntity<LocationDTO> addSimpleLocation(@RequestBody Map<String, Object> locationRequest) {
        try {
            // 从请求体中提取必要字段
            Long userId = Long.valueOf(locationRequest.get("userId").toString());
            Double latitude = Double.valueOf(locationRequest.get("latitude").toString());
            Double longitude = Double.valueOf(locationRequest.get("longitude").toString());
            String address = (String) locationRequest.get("address");

            // 创建LocationDTO对象
            LocationDTO location = new LocationDTO();
            location.setUserId(userId);
            location.setLatitude(latitude);
            location.setLongitude(longitude);
            location.setAddress(address);
            location.setTimestamp(new Date());

            // 保存位置
            LocationDTO savedLocation = locationService.addLocation(location);
            return ResponseEntity.ok(savedLocation);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }
} 